package client

import (
	"context"
	"fmt"
	"google.golang.org/grpc/resolver"
	"longmen/server/pkg/common/app/etcd"
	"time"
)

type BuilderOption func(*builder)

const schema = "discovery"

type builder struct {
	endpoint string
	discover *etcd.Registry
	timeout  time.Duration
}

//func WithTimeOut(timeout timehelper.Duration) BuilderOption {
//	return func(b *builder) {
//		b.timeout = timeout
//	}
//}

func NewBuilder(discover *etcd.Registry, opts ...BuilderOption) resolver.Builder {
	res := &builder{
		discover: discover,
	}
	for _, o := range opts {
		o(res)
	}
	return res
}

func (b *builder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {
	ctx, cancel := context.WithCancel(context.Background())
	fmt.Printf("target: %+v \n", target)
	watcher, err := b.discover.Watch(ctx, target.Endpoint())
	if err != nil {
		cancel()
		return nil, err
	}
	r := &discoveryResolver{
		w:      watcher,
		cons:   cc,
		ctx:    ctx,
		cancel: cancel,
	}
	go r.watch()
	return r, nil
}

func (b *builder) Scheme() string {
	return schema
}
